<script setup lang="ts">
// 获取系统信息，包含状态栏高度
import { getDonationListAPI, getDonationTypeAPI, getSchoolListAPI } from '@/services/home'
import type { Donation, DonationPage, DonationType, DonationVo, School } from '@/types/home'
import { onLoad } from '@dcloudio/uni-app'
import { ref, computed } from 'vue'
import CustomNavbar from './components/CustomNavbar.vue'
import BannerSwiper from './components/BannerSwiper.vue'
import type { SelectorPickerOnChangeEvent } from '@uni-helper/uni-app-types'
import { donationTypeStore } from '@/stores/modules/donationType'
import type { Activity } from '@/types/activity'
import { getActivityListAPI, type ActivityPage } from '@/services/activity'
import { useMemberStore } from '@/stores'

// 轮播图数据
const swiperList = ref<Activity[]>([])
//获取轮播图数据
const getBannerData = async () => {
  const res = await getActivityListAPI({ isBanner: 1 } as ActivityPage)
  swiperList.value = res.rows
}

/**选择学校 */
const schools = ref<School[]>([{ id: 0, schoolName: '全部' }]) //学校集合
//获取学校列表
const getSchoolList = async () => {
  const res = await getSchoolListAPI()
  schools.value.push(...res.rows)
  selectedSchoolIndex.value = schools.value.findIndex((item) => item.id === pageParams.schoolId)
}
//选择学校事件
const selectedSchoolIndex = ref(0) //学校索引
const schoolId = ref(0) //学校id
const memberStore = useMemberStore()
//选中的学校名称
const schoolText = computed(() => {
  return schools.value[selectedSchoolIndex.value].schoolName || '全部'
})
//选择学校事件
const handleSchoolChange = (e: SelectorPickerOnChangeEvent) => {
  selectedSchoolIndex.value = e.detail.value
  schoolId.value = schools.value[selectedSchoolIndex.value].id
  resetPageParams()
  getDonationData()
}

/**捐赠物种类选择*/
const selectedCategoryIndex = ref(0) //物品种类索引
const categories = ref<DonationType[]>([{ id: 0, typeName: '全部' }]) //捐赠物种类集合

// 选择物品种类
const handleCategoryChange = (e: SelectorPickerOnChangeEvent) => {
  selectedCategoryIndex.value = e.detail.value
  donation.value!.categoryId = categories.value[selectedCategoryIndex.value].id
  resetPageParams()
  getDonationData()
}
//获取物品种类列表
const donationStore = donationTypeStore() //物品种类列表持久层
const getDonationTypeList = async () => {
  if (donationStore.donationTypes.length > 0) {
    categories.value = donationStore.donationTypes
    return
  }
  const res = await getDonationTypeAPI()
  categories.value.push(...res.rows)

  donationStore.setDonationTypes(categories.value)
}

//选中的捐赠物种类
const categoryText = computed(() => {
  return categories.value[selectedCategoryIndex.value].typeName || '全部'
})

/**获取捐赠物列表 */
const donationList = ref<(DonationVo & { imgList: string[] })[]>([])

/**分页查询参数 */
/**分页条件 */
const donation = ref<Donation>({ status: 3 } as Donation)
const pageParams: Required<DonationPage> = {
  pageNum: 1,
  pageSize: 4,
  donation: donation.value,
  schoolId: memberStore.profile?.user.schoolId || schoolId.value,
}
//重置分页条件和页面数据
const resetPageParams = () => {
  pageParams.pageNum = 1
  pageParams.donation = donation.value
  pageParams.schoolId = memberStore.profile?.user.schoolId || schoolId.value
  pageParams.pageSize = 4
  donationList.value = []
  finish.value = false
}
// 获取捐赠物列表
const getDonationData = async () => {
  if (finish.value) {
    return uni.showToast({
      title: '没有更多数据了',
      icon: 'none',
    })
  }
  // 获取捐赠物列表
  const res = await getDonationListAPI(pageParams)
  //把图片字符串转换为数组
  const donationTempList = res.rows!.map((item) => {
    const imgList = item.images.split(',')
    return {
      ...item,
      imgList,
    }
  })
  donationList.value.push(...donationTempList) //数组追加
  if (donationList.value.length >= res.total) {
    finish.value = true
  } else {
    pageParams.pageNum++
  }
}
//没有更多数据标记
const finish = ref(false)
// 格式化日期的函数
const formatDate = (date: string | Date): string => {
  let dateObj: Date
  if (date instanceof Date) {
    dateObj = date // 如果是 Date 对象，直接使用
  } else {
    dateObj = new Date(date) // 如果是字符串，转换为 Date 对象
  }
  const year = dateObj.getFullYear()
  const month = String(dateObj.getMonth() + 1).padStart(2, '0') // 月份从0开始，需要加1，并补零
  const day = String(dateObj.getDate()).padStart(2, '0') // 补零
  return `${year}-${month}-${day}`
}
const loading = ref(false)
const onRefresh = async () => {
  loading.value = true
  finish.value = false
  donationList.value = []
  resetPageParams()
  await Promise.all([getSchoolList(), getBannerData(), getDonationData(), getDonationTypeList()])
  loading.value = false
}
//滚动触底
const onScrollToLower = () => {
  getDonationData()
}
onLoad(() => {
  getSchoolList()
  getBannerData()
  getDonationData()
  getDonationTypeList()
})
</script>

<template>
  <view class="index">
    <!-- 自定义导航栏 -->
    <CustomNavbar />
    <!-- 页面内容区域 -->
    <scroll-view
      class="content-scroll"
      @scrolltolower="onScrollToLower"
      refresher-enabled
      @refresherrefresh="onRefresh()"
      :refresher-triggered="loading"
      scroll-y
    >
      <!-- 轮播图区域 -->
      <view class="swiper-section">
        <BannerSwiper :list="swiperList" />
      </view>

      <!-- 闲置物品区域 - 两列布局 -->
      <view class="item-section">
        <!-- 级联下拉筛选器 -->
        <view class="filter-section">
          <!-- 将两个选择器放在同一行 -->
          <view class="filter-row filters-inline">
            <!-- 学校-小屋级联选择器 -->
            <picker
              :range="schools"
              range-key="schoolName"
              @change="handleSchoolChange"
              class="picker location-picker"
            >
              <view class="picker-box">
                <view class="picker-label">学校</view>
                <view class="picker-text">
                  <text>{{ schoolText }}</text>
                  <text class="arrow-down">&#9662;</text>
                </view>
              </view>
            </picker>

            <!-- 物品种类下拉框 -->
            <picker
              :range="categories"
              range-key="typeName"
              @change="handleCategoryChange"
              class="picker category-picker"
            >
              <view class="picker-box">
                <view class="picker-label">种类</view>
                <view class="picker-text">
                  <text>{{ categoryText }}</text>
                  <text class="arrow-down">&#9662;</text>
                </view>
              </view>
            </picker>
          </view>
        </view>

        <!-- 物品列表 - 两列网格布局 -->
        <view class="item-grid">
          <!-- 闲置物品1 -->
          <navigator
            class="item-card"
            :url="`/pages/item-detail/item-detail?donationId=${item.id}`"
            v-for="item in donationList"
            :key="item.id"
          >
            <image class="item-image" :src="item.imgList[0]" mode="aspectFill"></image>
            <view class="item-info">
              <view class="item-title">{{ item.description }}</view>
              <view class="user-info">
                <view class="user-left">
                  <image class="user-avatar" :src="item.userImage" mode="aspectFill"></image>
                  <text class="user-name">{{ item.donorName }}</text>
                </view>
                <view class="item-time">{{ formatDate(item.updateTime || '') }}</view>
              </view>
            </view>
          </navigator>
        </view>
      </view>
      <view class="loading-text">{{ finish ? '没有更多数据~' : '正在加载...' }}</view>
    </scroll-view>
  </view>
</template>

<style lang="scss">
.index {
  min-height: 100vh;
  background-color: #f2f2f2;
  position: relative;
}

.content-scroll {
  height: 100vh;
  box-sizing: border-box;
  padding-top: calc(44px + var(--status-bar-height, 20px) + 20px);
}

// 轮播图样式
.swiper-section {
  position: relative;
  width: 100%;
}

// 闲置物品样式 - 两列网格布局
.item-section {
  padding: 20rpx 0;

  // 筛选器样式
  .filter-section {
    padding: 16rpx 24rpx;
    background-color: #fff;
    border-radius: 12rpx;
    margin: 0 24rpx 16rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

    .filter-row {
      margin-bottom: 0;

      &.filters-inline {
        display: flex;
        justify-content: space-between;

        .picker {
          width: 48%; // 设置宽度为略小于50%，留出间距
        }
      }
    }

    .location-picker,
    .category-picker {
      width: 100%;
    }

    .picker-box {
      display: flex;
      align-items: center;
      padding: 12rpx 0;
    }

    .picker-label {
      font-size: 28rpx;
      color: #666;
      padding-right: 20rpx;
      position: relative;
      display: flex;
      align-items: center;

      &::after {
        content: '';
        position: absolute;
        right: 10rpx;
        top: 50%;
        transform: translateY(-50%);
        width: 1px;
        height: 24rpx;
        background-color: #e5e5e5;
      }
    }

    .picker-text {
      display: flex;
      align-items: center;
      font-size: 28rpx;
      color: #333;
      flex: 1;
      justify-content: space-between;

      .arrow-down {
        font-size: 24rpx;
        color: #aaa;
        margin-left: 8rpx;
      }
    }
  }

  .item-grid {
    display: flex;
    flex-wrap: wrap;
    padding: 0 12rpx;

    .item-card {
      width: calc(50% - 16rpx);
      margin: 8rpx;
      background-color: #fff;
      border-radius: 12rpx;
      overflow: hidden;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

      .item-image {
        width: 100%;
        height: 320rpx;
        object-fit: cover;
      }

      .item-info {
        padding: 16rpx;

        .item-title {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 20rpx;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .user-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 6rpx 0;

          .user-left {
            display: flex;
            align-items: center;
            flex: 1;
            overflow: hidden;

            .user-avatar {
              width: 40rpx;
              height: 40rpx;
              border-radius: 50%;
              margin-right: 10rpx;
              flex-shrink: 0;
            }

            .user-name {
              font-size: 24rpx;
              color: #666;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }

          .item-time {
            font-size: 22rpx;
            color: #999;
            flex-shrink: 0;
            margin-left: 8rpx;
          }
        }
      }
    }
  }
}

// 加载提示文字
.loading-text {
  text-align: center;
  font-size: 28rpx;
  color: #666;
  padding: 20rpx 0;
}

// 字体图标样式
@font-face {
  font-family: 'iconfont';
  src: url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAAUYAAsAAAAACngAAATKAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHFQGYACDXgqHRIY8ATYCJAMcCxAABCAFhGcHXBvRCMgOJSHBwABgAABgBN/v97nPvfd9INFoyaZ3ETVN0kQimcQbpEgIdSKJ0EqC1pOa/P/32/4+M25mCLlDJGqaMOlbvWxidgK7aWJemujwNjQPe6EAeMBWTKqtbb+0gVKI1USq8t/soS6lPtR7qcRFYS4KfOg7HBcVFfBDCzYAxw8U0P0bY9u0EGABHVdtOyiwgZ6F10NwoD+3EwimRR/k4/XdC4hKowugK69OMUTlKNCG0NNrZ+YsfqJTn16lnwB8tL8//sNMREmqDK/cezWjYfnX8nMp6v+pxnMQQeZ2DmwVGfuAQryutb1CBrN9GIL1tyYugWBPUr+Wn8PP5Z9L//+Pr4pqJBoNNiQYSu9fvEhWNVEL7A+wfQa/lpWKX2cpfm0xGcISUjKEFaRiCGsGrCXEZaR2Uc1+JNNWaR9QvAf5G9KzV6zKNcoYL1LNSXVypSGLrq/Rjbg8hs0cj9H1OOc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ecMU05Y7U5dZYBYsVnB0IkxOgQbDCZBKLiAsZQ0jFFnP/9IKptFnBJMPuIhzBq1RfYEXQ2rYbZ9N5wJUuhIqZAJAfSBTJQHZxQLweuuFYxUrhEQQHFUxqjSY4xagvnCK1Qr1K8vsp1ECVajLgRRxIlWpwYrqwpSmQ5VVxXJ8e93P3mMQ==')
    format('woff2');
  font-weight: normal;
  font-style: normal;
}

.iconfont {
  font-family: 'iconfont' !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-search:before {
  content: '\e628';
}

.icon-camera:before {
  content: '\e618';
}

.icon-more:before {
  content: '\e684';
}

.icon-like:before {
  content: '\e8ab';
}

.icon-arrow-down:before {
  content: '\e665';
}
</style>
